package com.gopay.scheduler.job;

import com.gopay.common.domain.acps.AcctProd;
import com.gopay.common.domain.acps.model.AcctMastBean;
import com.gopay.common.util.FileUtil;
import com.gopay.cron.service.cloud.CloudAccountStatementGenService;
import com.gopay.remote.acps.service.AcctTransRemoteService;
import com.gopay.scheduler.GopayBaseJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.gopay.common.constants.YnFlag.y;

public class CloudAccountStatementGenJob extends GopayBaseJob {

    // 日志
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @Value("#{webProperties['cloud.statementOfAccountGen.custIds']}")
    private String custIds;

    @Value("#{webProperties['cloud.statementOfAccountGen.basePath']}")
    private String basePath;

    @Resource(name = "cloudAccountStatementGenService")
    private CloudAccountStatementGenService cloudAccountStatementGenService;

    @Resource(name = "acctTransRemoteService")
    private AcctTransRemoteService acctTransRemoteService;

    @Override
    public void doJobInternal() {
        //1.生成对账文件

        // 获取需要生成对账文件的平台账户ID（总账户的custId）
        Set<String> custIdSet = getPlatformCustIds();
        if(custIdSet != null && custIdSet.isEmpty()) {
            logger.error("job end：没有配置需要生成对账文件的custId，job结束");
            return;
        }
        logger.error("需要生成对账文件的custId："+this.custIds);

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE,-1);
        String ymd = new SimpleDateFormat( "yyyy-MM-dd").format(cal.getTime());

        //logger.info("生成"+ymd+"对账文件");

        for(String custId : custIdSet) {
            List<AcctMastBean> accts = acctTransRemoteService.getAccounts(custId);
            for(AcctMastBean acct : accts) {
                //只有云账户和普通账户才生成
                if(AcctProd.CLOUD.toString().equals(acct.getProdCodeStr())
                        || AcctProd.GNST.toString().equals(acct.getProdCodeStr())) {
                    logger.info("custId:"+custId+",acctId:"+acct.getAcctId()+",acctProd:"+acct.getProdCodeStr());
                    cloudAccountStatementGenService.genFile(basePath,ymd,custId,acct.getAcctId(),acct.getProdCodeStr());
                }
            }
        }
        logger.error("生成对账文件,checkDate="+ymd+",custId="+custIds);

        //2.清除三十天之前的文件
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,-30);
        String rmd = new SimpleDateFormat( "yyyy-MM-dd").format(calendar.getTime());
        logger.error("开始清除三十天之前的文件,清除的日期为："+rmd);
        File path = new File(basePath + rmd);
        deleteFile(path);

        //3.清空前一天下载接口调用次数
        logger.error("开始清空前一天下载接口调用次数，custIds="+this.custIds);
        cloudAccountStatementGenService.cleanYesterdayFileDownloadNum(getPlatformCustIds());

    }


    private Set<String> getPlatformCustIds() {
        Set<String> set = new HashSet<>();
        if(this.custIds != null && !"".equals(this.custIds)) {
            if(this.custIds.contains(",")) {
                String[] strArr = this.custIds.split(",");
                for(int i = 0; i < strArr.length; i++) {
                    set.add(strArr[i]);
                }
            } else {
                set.add(this.custIds);
            }
        }
        return set;
    }

    private void deleteFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (int i = 0;i < files.length;i ++) {
                    this.deleteFile(files[i]);
                }
                file.delete();//删除文件夹
            }
        }
    }

}
